//
//  AppDelegate.m
//  ShangChengMoBan
//
//  Created by 张铁军 on 16/8/13.
//  Copyright (c) 2016年 ping. All rights reserved.
//

#import "AppDelegate.h"
#import "ShouYeMainViewController.h"
#import "FenLeiMainViewController.h"
#import "GouWuCheMainViewController.h"
#import "WoDeMainViewController.h"
#import "IQKeyboardManager.h"

#import <AudioToolbox/AudioToolbox.h>

@interface AppDelegate ()
@property(nonatomic,strong)NSMutableArray * array;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [APIManager sheZhiIP:IP];
   
    [self tabBarView];
//    ios中滑动视图怎么阻止自动让出状态栏20像素
//    weixin
//    weibo
//    qq
//    qzone
//    DemonZXY2Vx | 浏览 1142 次 2014-11-18 23:15
//    2014-11-19 02:20
//    最佳答案
//    
//    iPhone软键盘占据216像素高，这对于iPhone仅仅320*480像素的屏幕来说，不能说不是一个很糟糕的事情。 为了避免输入控件被弹出的216像素高的软键盘所遮挡，程序员们想出了各种各样的方式，在软键盘弹出时调整窗口视图的尺寸。
//    程序员们普遍采用的一种方式，是监听软键盘事件。当软键盘弹出时，窗体的View被上移，当软键盘隐藏时，窗体的View恢复原来位置，这样就避免了输入控件被遮挡。
//    但是，由于SDK的原因，在View移动的过程中，会导致一个“20像素Bug”的问题。即键盘隐藏后，View下移的位置会偏离原来位置20个像素。这个Bug最直观的表现是，View的最下端露出了20像素的空白。
//    解决20像素的bug的方法很简单，就是在隐藏键盘时，手动将View的 y坐标下移20像素。
//    但是，对于另一种情况，我们做这样的调整则是多余的，它反而会在View的上端露出20像素空白。
//    SDK的这种Bug让我们无所适从。到底什么时候需要调整View的20像素，什么时候不需要调整呢？
//    问题就在于状态栏上。状态栏是否可视，直接影响这20像素是否需要调整。很显然，当statusBarHidden为NO（默认）时，view的有效高度为480，否则view的有效高度只有460而已。我们在xib中设计view的位置的时候，不管statusbar是否为None，view的origin都是(0,0)，但SDK在加载xib之后，会根据statusBarHidden的属性自动调整view的位置，使得view最上端的20像素不会被状态栏所遮盖。
//    也就是说，当statusBarHidden为NO时，虽然我们在IB中看到view的origin是（0,0），但实际运行时，view的origin已经被SDK调整为正确的(20,0)。
//    因此，在键盘隐藏时，程序员不应该把view移动到(0,0)处，而应该调整到(20,0)处。因为SDK已经不会为我们做这件事情，我们得用自己的代码来做。
//    
//    当然，如果你确实不需要在你的app中显示一个状态栏，我们会在application:didfinishLaunchWithOption:方法中这样做 ：
    
    //注册信鸽
    [self zhuCeXinGeWithOptions:launchOptions];
    [self autoKeyboard];//键盘自动适应
    return YES;
    
}

#pragma mark 键盘自动适应
-(void)autoKeyboard{
    
    //Enabling keyboard manager
    [[IQKeyboardManager sharedManager] setEnable:YES];
    
    [[IQKeyboardManager sharedManager] setKeyboardDistanceFromTextField:0];
    //Enabling autoToolbar behaviour. If It is set to NO. You have to manually create UIToolbar for keyboard.
    
    
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    
    //Setting toolbar behavious to IQAutoToolbarBySubviews. Set it to IQAutoToolbarByTag to manage previous/next according to UITextField's tag property in increasing order.
    [[IQKeyboardManager sharedManager] setToolbarManageBehaviour:IQAutoToolbarBySubviews];
    
    //Resign textField if touched outside of UITextField/UITextView.
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
    
    //Giving permission to modify TextView's frame
    [[IQKeyboardManager sharedManager] setCanAdjustTextView:YES];
    
}


-(void)tabBarView{
    
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    
   
    ShouYeMainViewController *shouYE = [[ShouYeMainViewController alloc] init];
    [arr addObject:shouYE];
   
    
    FenLeiMainViewController *fenLeiview = [[FenLeiMainViewController alloc]init];
    [arr addObject:fenLeiview];
    
    GouWuCheMainViewController *gouWuView = [[GouWuCheMainViewController alloc]init];
    [arr addObject:gouWuView];
    
    WoDeMainViewController *meView = [[WoDeMainViewController alloc]init];
    [arr addObject:meView];

    NSArray * zhengChangAry = @[@"首页",@"分类",@"购物车",@"我的"];
    NSArray * highlightAry = @[@"首页-变色",@"分类-变色",@"购物车-变色",@"我的-变色"];
    NSArray *textAry = @[@"首页",@"分类",@"购物车",@"我的"];
    
    NSMutableArray *newArr = [[NSMutableArray alloc] init];
    for (int i = 0; i<arr.count; i++) {
        UIViewController *vc = [arr objectAtIndex:i];
        UIImage *image=[[UIImage imageNamed:[zhengChangAry objectAtIndex:i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImage *image2 =[[UIImage imageNamed:[highlightAry objectAtIndex:i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];// 始终绘制图片原始状态，不使用Tint Color。
        vc.tabBarItem = [[UITabBarItem alloc]initWithTitle:[textAry objectAtIndex:i] image:image selectedImage:image2];
        [newArr addObject:vc];
    }
    //    UITabBarController *tabbar = [[UITabBarController alloc] init];
    //    tabbar.viewControllers = newArr;
    //    [tabbar setSelectedIndex:0];
    //    tabbar.tabBar.tintColor = ZONGCOLOR;
    
    UITabBarController *custonTabbarView = [[UITabBarController alloc]init];
    custonTabbarView.viewControllers = newArr;
    //        custonTabbarView.tabBar.hidden = YES;
    custonTabbarView.selectedViewController = shouYE;
    custonTabbarView.tabBar.tintColor = ZONGCOLOR;
    
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:custonTabbarView];
    nav.navigationBarHidden= YES;
    nav.navigationController.navigationBar.translucent = YES;
        nav.interactivePopGestureRecognizer.enabled = YES;
    self.window.rootViewController = nav;
    NSUserDefaults *JFSC = [NSUserDefaults standardUserDefaults];
    //增加标识，用于判断是否是第一次启动应用...
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunchedWUSI"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunchedWUSI"];
        NSLog(@"第一次启动!");
        NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
        [d setObject:@"0" forKey:@"isFirstToQianDao"];
        [JFSC setObject:@"0" forKey:@"JFSC"];
        [JFSC synchronize];
    }else{
        [JFSC setObject:@"1" forKey:@"JFSC"];
        [JFSC synchronize];
    }
    
}




- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSString *str = [XGPush registerDevice:deviceToken];
    // 打印获取的deviceToken的字符串
    NSLog(@"deviceTokenStr is %@",str);
}


#pragma 推送有关

-(void)zhuCeXinGeWithOptions:(NSDictionary *)launchOptions {
    
    [XGPush startApp:2200154870 appKey:@"ILA8X4843SEU"];
    //     [XGPush startApp:2200156453 appKey:@"IRWXG2P1577Q"];
    [XGPush initForReregister:^{
        //如果变成需要注册状态
        if(![XGPush isUnRegisterStatus])
        {
            //iOS8注册push方法
            float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
            
            if(sysVer < 8){
                [self registerPush];
            }
            else{
                //                [self registerPush];
                [self registerPushForIOS8];
            }
        }
    }];
    
    //推送反馈回调版本示例
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush]handleLaunching's successBlock");
    };
    
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush]handleLaunching's errorBlock");
    };
    
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    //清除所有通知(包含本地通知)
    //[[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    [XGPush handleLaunching:launchOptions successCallback:successBlock errorCallback:errorBlock];
}

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    //notification是发送推送时传入的字典信息
    [XGPush localNotificationAtFrontEnd:notification userInfoKey:@"clockID" userInfoValue:@"myid"];
    //删除推送列表中的这一条
    [XGPush delLocalNotification:notification];
    
    //    //清空推送列表
    //    [XGPush clearLocalNotifications];
}

- (void)addMessageFromRemoteNotification:(NSDictionary*)userInfo updateUI:(BOOL)updateUI{
    
}

-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler
{
    
    
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
    UIApplication *app = [UIApplication sharedApplication];
    //获取本地推送数组
    NSArray *localArray = [app scheduledLocalNotifications];
    NSLog(@"tongzhi %@",localArray);
    
    NSLog(@"%@",userInfo);
    
    NSLog(@"%@",userInfo);
    
    [XGPush handleReceiveNotification:userInfo];
    if (application.applicationState != UIApplicationStateActive){
        //        XiaoXiZhongXinViewController * immerView = [[XiaoXiZhongXinViewController alloc]init];
        //        [(UINavigationController *)self.window.rootViewController pushViewController:immerView animated:YES];
        
    }else{
        //声音震动
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        AudioServicesPlaySystemSound(1007);
    }
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}


- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    //如果deviceToken获取不到会进入此事件
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    
    [defaults setObject:@"" forKey:@"deviceToken"];
    
    [defaults synchronize];
    
    NSString *str = [NSString stringWithFormat: @"Error: %@",err];
    
    NSLog(@"deviceToken ERROR : %@",str);
}


- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    //    NSLog(@"....%@",[defaults objectForKey:@"xuanZhuan"]);
    
    if ([[defaults objectForKey:@"xuanZhuan"]intValue] == 1) {
        return UIInterfaceOrientationMaskLandscape
        ;
    }else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

- (void)registerPushForIOS8{
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    
    //Types
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    
    //Actions
    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
    
    acceptAction.identifier = @"ACCEPT_IDENTIFIER";
    acceptAction.title = @"Accept";
    
    acceptAction.activationMode = UIUserNotificationActivationModeForeground;
    acceptAction.destructive = NO;
    acceptAction.authenticationRequired = NO;
    
    //Categories
    UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
    
    inviteCategory.identifier = @"INVITE_CATEGORY";
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextDefault];
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextMinimal];
    
    NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
    
    
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}

- (void)registerPush{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}

@end
